import React, { useCallback, useState, useEffect } from 'react';
import ReactFlow, {
  Controls,
  Background,
  applyNodeChanges,
  applyEdgeChanges,
  addEdge,
  Connection,
  Edge,
  Node,
  NodeChange,
  EdgeChange,
  Position
} from 'reactflow';
import 'reactflow/dist/style.css';
import './workflow.css';
import NodeEditor from './node-editor';
import { message, Layout, Card, Typography, Button, Input, Space } from 'antd';
import { SaveOutlined, PlayCircleOutlined, PlusOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { workflowService } from '../services/workflow.service';
import { commonAPI } from '../services/api';
import { useLocation, useNavigate } from 'react-router-dom';

const { Content } = Layout;
const { Title } = Typography;

const initialNodes: Node[] = [
  {
    id: '1',
    position: { x: 0, y: 0 },
    data: { label: '开始' },
    type: 'input', 
    sourcePosition: 'right' as Position,
    style: {
      width: 50,
      height: 50,
      borderRadius: '50%',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      padding: 10
    }
  },
];

const initialEdges: Edge[] = [];

interface WorkflowProps {
  workflowId?: string | null;
  onSaved?: () => void;
}

export default function Workflow({ workflowId, onSaved }: WorkflowProps = {}) {
  const [nodes, setNodes] = React.useState<Node[]>(initialNodes);
  const [edges, setEdges] = React.useState<Edge[]>(initialEdges);
  const [workflowName, setWorkflowName] = useState('');
  const [showNodeTypes, setShowNodeTypes] = useState(false);
  const [hoveredNodeType, setHoveredNodeType] = useState<'default' | 'output' | null>(null);
  const [running, setRunning] = useState(false);
  const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);
  const [tools, setTools] = useState<any[]>([]);
  const location = useLocation();
  const navigate = useNavigate();

  const onNodesChange = useCallback(
    (changes: NodeChange[]) => setNodes((nds) => applyNodeChanges(changes, nds)),
    []
  );

  const onEdgesChange = useCallback(
    (changes: EdgeChange[]) => setEdges((eds) => applyEdgeChanges(changes, eds)),
    []
  );

  const onConnect = useCallback(
    (connection: Connection) => setEdges((eds) => addEdge(connection, eds)),
    []
  );

  const addNode = (type: 'default' | 'output') => {
    const newNode: Node = {
      id: `${Date.now()}`,
      position: { 
        x: nodes[nodes.length - 1].position.x + 100,
        y: nodes[nodes.length - 1].position.y + 50
      },
      data: { label: type === 'output' ? '结束' : '新节点' },
      type: type,
      targetPosition: Position.Left,
      sourcePosition: type === 'output' ? undefined : Position.Right,
      style: type === 'output' ? {
        width: 50,
        height: 50,
        borderRadius: '50%',
        display: 'flex',
        alignItems: 'center', 
        justifyContent: 'center',
        padding: 10
      } : {
        width: 150,
        height: 45,
        padding: 15
      }
    };
    setNodes((nds) => nds.concat(newNode));
  };

  const handleSave = async () => {
    try {
      const workflow_Id = workflowId || new URLSearchParams(location.search).get('workflow_id');
      if (workflow_Id) {
        // 更新已有工作流
        await workflowService.saveWorkflow({ 
          workflow_id: workflow_Id, 
          workflow_name: workflowName,   
          nodes, 
          edges  
        });
        message.success('工作流已更新');
      } else {
        await workflowService.saveWorkflow({ 
          workflow_name: workflowName,
          nodes, 
          edges 
        });
        message.success('保存成功');
      }
      
      // 调用保存成功回调
      if (onSaved) {
        onSaved();
      }
     
    } catch (error) {
      console.error('保存错误:', error);
      message.error(
        (error instanceof Error) ? error.message : '保存异常'
      );
    }
  };

  const handleRun = async () => {
    setRunning(true);
    
    const executionOrder = nodes.sort((a, b) => a.position.x - b.position.x);
    
    setEdges(eds => eds.map(edge => ({
      ...edge,
      style: { ...edge.style, stroke: '#4CAF50' }
    })));

    for (const node of executionOrder) {
      setNodes(nds => nds.map(n => 
        n.id === node.id 
          ? { ...n, className: 'running-effect' }
          : n
      ));
      await new Promise(resolve => setTimeout(resolve, 1000));
    }

    setRunning(false);
    setNodes(nds => nds.map(n => ({ 
      ...n, 
      className: 'completed-effect',
      style: { 
        ...n.style, 
        backgroundColor: '#4CAF50',
        color: 'white'
      }
    })));
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (['Delete', 'Backspace'].includes(e.key)) {
      const selectedEdges = edges.filter(edge => edge.selected);
      if (selectedEdges.length > 0) {
        setEdges(prev => prev.filter(edge => !edge.selected));
      }
    }
  };

  useEffect(() => {
    const fetchTools = async () => {
      try {
        const data = await commonAPI.fetchTools();
        setTools(data.data.tool_list);
      } catch (error) {
        console.error('获取工具列表失败:', error);
        alert('无法加载工具列表');
      }
    };
    fetchTools();
  }, []);

  useEffect(() => {
    const fetchWorkflow = async () => {
      const id = workflowId || new URLSearchParams(window.location.search).get('workflow_id');
      
      if (id) {
        try {
          const response = await workflowService.fetchWorkflowInfo(id);
          setNodes(response.nodes);
          setEdges(response.edges);
          setWorkflowName(response.workflow_name || '');
        } catch (error) {
          console.error('加载工作流失败:', error);
          message.error('无法加载工作流配置');
        }
      }
    };

    fetchWorkflow();
  }, [workflowId]);

  return (
    <Layout className="site-layout">
      <Content style={{ margin: '0 16px', padding: 24, minHeight: 280 }}>
        <Card bordered={false} bodyStyle={{ padding: 0 }}>
          <div style={{ padding: '16px 24px', borderBottom: '1px solid #f0f0f0' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Space>
                <Button 
                  icon={<ArrowLeftOutlined />} 
                  onClick={onSaved || (() => navigate('/dev_tools/workflow-list'))}
                >
                  返回列表
                </Button>
                <Input
                  placeholder="输入流程名称"
                  value={workflowName}
                  onChange={(e) => setWorkflowName(e.target.value)}
                  style={{ width: 200 }}
                />
              </Space>
              <Space>
                <Button
                  type="primary"
                  icon={<SaveOutlined />}
                  onClick={handleSave}
                >
                  保存流程
                </Button>
                <Button
                  type="primary"
                  icon={<PlayCircleOutlined />}
                  onClick={handleRun}
                  loading={running}
                >
                  运行流程
                </Button>
              </Space>
            </div>
          </div>
          
          <div style={{ height: 'calc(100vh - 200px)', position: 'relative' }}>
            <ReactFlow
              nodes={nodes}
              edges={edges}
              onNodesChange={onNodesChange}
              onEdgesChange={onEdgesChange}
              onConnect={onConnect}
              onNodeClick={(event, node) => {
                if (node.type === 'default') {
                  setSelectedNodeId(node.id);
                }
              }}
              fitView
              attributionPosition="bottom-left"
              onKeyDown={handleKeyDown}
            >
              <Controls />
              <Background color="#aaa" gap={16} />
            </ReactFlow>
            
            {showNodeTypes && (
              <div className="node-types">
                <div
                  className={`node-type ${hoveredNodeType === 'default' ? 'hovered' : ''}`}
                  onClick={() => addNode('default')}
                  onMouseEnter={() => setHoveredNodeType('default')}
                  onMouseLeave={() => setHoveredNodeType(null)}
                >
                  处理节点
                </div>
                <div
                  className={`node-type ${hoveredNodeType === 'output' ? 'hovered' : ''}`}
                  onClick={() => addNode('output')}
                  onMouseEnter={() => setHoveredNodeType('output')}
                  onMouseLeave={() => setHoveredNodeType(null)}
                >
                  结束节点
                </div>
              </div>
            )}
            
            <Button
              type="primary"
              shape="circle"
              icon={<PlusOutlined />}
              className="add-node-button"
              onClick={() => setShowNodeTypes(!showNodeTypes)}
            />
            
            {selectedNodeId && (
              <NodeEditor
                selectedNodeId={selectedNodeId}
                nodes={nodes}
                setNodes={setNodes}
                onClose={() => setSelectedNodeId(null)}
                tools={tools}
              />
            )}
          </div>
        </Card>
      </Content>
    </Layout>
  );
}
